<?php


namespace App\Models;


class ImFriendsCircleComments extends BaseModel
{
    //朋友圈评论列表
    protected $table = 'im_friends_circle_comments';

    //评论者信息
    public function user()
    {
        return $this->belongsTo(ImUsers::class, 'friend_id', 'id')
            ->select(['id', 'nickname', 'headimg']);
    }

    // 被回复人的信息
    public function toUser()
    {
        return $this->belongsTo(ImUsers::class, 'to_id', 'id')
            ->select(['id', 'nickname', 'headimg']);
    }

    /**
     * @desc 发布评论
     * @param array $input 传过来数组对象
     * @param array $user 用户对象
     * @param array $headerList 公共头
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function addComment($input, $user)
    {
        $userId = $user->id;
        $commentId = $input['comment_id'] ?? 0; // 评论的主键id
        $imFriendsCircle = new ImFriendsCircle();
        $imFriendsCircle = $imFriendsCircle->where(['id'=>$input['fc_id']])->first();
        if (!$imFriendsCircle)
        {
            return ['code' => 1, 'msg' => '朋友圈已被删'];
        }

        $this->to_id = !empty($input['to_id']) ? $input['to_id'] : $imFriendsCircle['user_id']; // 评论的用户对象

        // 查询好友是否好友关系
        $imUserFriend = new ImUserFriend();
        $imUserFriend = $imUserFriend->where(['user_id'=>$userId, 'other_uid'=>$this->to_id, 'status'=>1])->first();
        if (!$imUserFriend && ($userId != $imFriendsCircle['user_id']))
        {
            return ['code' => 1, 'msg' => '非好友不能评论'];
        }

        // 查询评论的父id
        $commentInfo = $this->find($commentId);
        $this->pid = !empty($commentInfo['pid']) ? $commentInfo['pid'] : $commentId;
        $this->fc_id = $input['fc_id'];
        $this->friend_id = $userId;
        $this->content = $input['content'];
        $flag = $this->save();
        if (!$flag)
        {
            return ['code' => 1, 'msg' => '评论失败'];
        }

        $imFriendsCircle->increment('comment_count');

        // 评论插入到消息表
        if ($this->to_id != $userId )
        {
            $ImNotification = new ImNotification();
            $ImNotification->addMessage($this->to_id, 2, $userId, $imFriendsCircle['id'], '评论', $this->id);
        }


        return ['code' => 0, 'id' => $this->id, 'msg' => '评论成功','data'=>['content'=>$input['content'], 'user_id'=>$userId, 'nickname'=>$user->nickname]];
    }

    /**
     * @desc 评论列表
     * @param int $fcId 文章的列表
     * @param int $userId 当前uid
     * @param int $limit
     * @param int $offset
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/29 10:14
     */
    public function commentList($fcId, $userId = 0, $limit = 10, $offset = 0)
    {
        $list = $this->select('id', 'fc_id', 'friend_id', 'content', 'pid', 'to_id', 'created_at')->with(['user','toUser'])->where(['fc_id'=>$fcId])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return $list;
    }

}
